import React, { Component } from 'react';
import ReactEcharts from 'echarts-for-react';
import axios from '../api'
import xyz from './xyz'

import echarts from 'echarts';

export default class CustomSta extends Component {

  constructor(props) {
    super(props)
    this.state = {
      option: {},
      startAngle: 90
    }
  }

  componentWillMount () {
    echarts.registerTheme('xyz', xyz);
  }

  componentDidMount () {
    this.tick()
    this.timerID = setInterval(
      () => this.tick(),
      15 * 60 * 1000
    );
  }

  componentWillUnmount () {
    clearInterval(this.timerID);
  }

  tick () {
    axios.get('/custom_sta').then(({ data }) => this.genData(data))
  }

  genData (data) {
    let n1 = 1
    let n2 = 0.3
    setInterval(() => {
      let x = n1
      n1 = n2
      n2 = x
      this.roundSet(n1, n2,data)
    }, 5000)
  }

  round (n1, n2, sample, center) {
    const itemStyle = {
      color: {
        type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
        colorStops: [
          { offset: 0, color: '#13C1FF' },
          { offset: 1, color: '#4700DE' }],
      }
    }
    const itemStyleDefault = { color: '#040e29' }
    const seriesItem = (r, d, s = false) => ({
      type: 'pie', center, radius: r, clockwise: false, avoidLabelOverlap: false,
      startAngle: s ? this.state.startAngle : 10,
      data: d.map((item, idx) => Object.assign({}, item, { itemStyle: idx > 0 ? itemStyleDefault : itemStyle })),
      labelLine: { show: false },
    })
    const dataNumber =  [sample].map(({ name, value }) => ({
      name: `${name}\n${value}`,
      value,
      label: { position: 'center', color: '#FEE349', fontSize: 14, fontWeight:'bold' },
    }))
    return [seriesItem(['30%', '31%'], [{ value: 1,tooptip:{} }]), seriesItem(['25%', '30%'], [{ value: n1 }, { value: n2 }]), seriesItem(['25%', '25%'], dataNumber)]
  }

  roundSet (n1,n2,data) {
    const centerList = [
      ['18%', '25%'], ['50%', '25%'], ['82%', '25%'],
      ['18%', '75%'], ['50%', '75%'], ['82%', '75%']]
    const temp = data.map((item,idx)=>this.round(n1,n2,item,centerList[idx]))
    const series = [].concat(...temp)
    this.setState({option:{series}})
  }

  render () {
    return (
      <ReactEcharts
        option={this.state.option}
        notMerge={true}
        lazyUpdate={true}
        style={{ height: '100%' }}
        theme={'xyz'} />
    )
  }
}